<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm"  :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="名称" prop="name">
        <el-input
          v-model="queryParams.name"
          placeholder="请输入名称"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="金额" prop="amount">
        <el-input
          v-model="queryParams.amount"
          placeholder="请输入金额"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="有效期" prop="expir">
        <el-input
          v-model="queryParams.expir"
          placeholder="请输入有效期"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
  </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
           type="primary"
           plain
           icon="Plus"
           @click="handleAdd"
           v-hasPermi="['system:package:add']"
        >新增</el-button>
     </el-col>
     <el-col :span="1.5">
        <el-button
           type="success"
           plain
           icon="Edit"
           :disabled="single"
           @click="handleUpdate"
           v-hasPermi="['system:package:edit']"
        >修改</el-button>
     </el-col>
     <el-col :span="1.5">
        <el-button
           type="danger"
           plain
           icon="Delete"
           :disabled="multiple"
           @click="handleDelete"
           v-hasPermi="['system:package:remove']"
        >删除</el-button>
     </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="packageList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column type="index" label="序号" width="50" align="center" />
      <el-table-column label="名称" align="center" prop="name" />
      <el-table-column label="金额" align="center" prop="amount" />
      <el-table-column label="有效期" align="center">
        <template #default="scope">
          {{ scope.row.expir }}{{ dictLabel(scope.row.expirUnit, expir_unit) }}
        </template>
      </el-table-column>
      <el-table-column label="备注" align="center" prop="remark" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['system:package:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['system:package:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <pagination
      v-show="total>0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改VIP套餐对话框 -->
    <el-dialog :title="title" v-model="open" width="500px" append-to-body>
      <el-form ref="formRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入名称" />
        </el-form-item>
        <el-form-item label="金额" prop="amount">
          <el-input 
            v-model="form.amount" 
            placeholder="请输入金额" 
            @input="(val) => form.amount = val.replace(/[^\d.]/g, '').replace(/\.{2,}/g, '.').replace(/^(\d*\.\d{0,2}).*$/,'$1')"
          />
        </el-form-item>
        <el-form-item label="有效期" prop="expir">
          <el-input-number 
            v-model="form.expir" 
            :min="1" 
            controls-position="right"
            style="width: 200px"
            placeholder="请输入有效期"
          />
          <el-select 
            v-model="form.expirUnit" 
            style="width: 80px; margin-left: 10px"
          >
            <el-option
              v-for="dict in expir_unit"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" type="textarea" placeholder="请输入内容" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Package">
import { ref, reactive, getCurrentInstance } from 'vue';
import { listPackage, getPackage, delPackage, addPackage, updatePackage } from "@/api/system/package";

const { proxy } = getCurrentInstance()

const { expir_unit } = proxy.useDict("expir_unit");


// 添加金额验证规则
const validateAmount = (_rule, value, callback) => {
  if (value === '') {
    callback(new Error('金额不能为空'))
  } else if (!/^\d+(\.\d{1,2})?$/.test(value)) {
    callback(new Error('请输入正确的金额格式'))
  } else if (value <= 0) {
    callback(new Error('金额必须大于0'))
  } else {
    callback()
  }
}

// 响应式数据定义
const loading = ref(true)
const ids = ref([])
const single = ref(true)
const multiple = ref(true)
const showSearch = ref(true)
const total = ref(0)
const packageList = ref([])
const title = ref("")
const open = ref(false)

// 查询参数
const queryParams = reactive({
  pageNum: 1,
  pageSize: 10,
  name: null,
  amount: null,
  expir: null
})

// 定义初始表单数据
const initialForm = {
  id: undefined,
  name: undefined,
  amount: undefined,
  expir: undefined,
  expirUnit: "0",
  createBy: undefined,
  createTime: undefined,
  updateBy: undefined,
  updateTime: undefined,
  remark: undefined
}

// 表单参数
const form = reactive({
  id: undefined,
  name: undefined,
  amount: undefined,
  expir: undefined,
  expirUnit: "0",
  createBy: undefined,
  createTime: undefined,
  updateBy: undefined,
  updateTime: undefined,
  remark: undefined
})

// 表单校验规则
const rules = {
  name: [
    { required: true, message: "名称不能为空", trigger: "blur" }
  ],
  amount: [
    { required: true, message: "金额不能为空", trigger: "blur" },
    { validator: validateAmount, trigger: ['blur', 'change'] }
  ],
  expir: [
    { required: true, message: "有效期不能为空", trigger: "blur" },
    { type: 'number', message: '有效期必须为数字', trigger: ['blur', 'change'] }
  ],
  expirUnit: [
    { required: true, message: "有效期单位不能为空", trigger: "change" }
  ]
}

// 有效期单位选项
const expirUnitOptions = {
  0: '天',
  1: '月', 
  2: '年'
}

// 表单ref
const formRef = ref()

/** 查询VIP套餐列表 */
function getList() {
  loading.value = true
  listPackage(queryParams).then(response => {
    packageList.value = response.rows
    total.value = response.total
    loading.value = false
  })
}

// 取消按钮
function cancel() {
  open.value = false
  reset()
}

// 表单重置
function reset() {
  form.id = undefined
  form.name = undefined
  form.amount = undefined
  form.expir = undefined
  form.expirUnit = "0"
  form.createBy = undefined
  form.createTime = undefined
  form.updateBy = undefined
  form.updateTime = undefined
  form.remark = undefined
  
  proxy.resetForm("formRef")
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.pageNum = 1
  getList()
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryForm")
  handleQuery()
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.id)
  single.value = selection.length!==1
  multiple.value = !selection.length
}

/** 新增按钮操作 */
function handleAdd() {
  reset()
  open.value = true
  title.value = "添加VIP套餐"
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset()
  const id = row.id || ids.value
  getPackage(id).then(response => {
    Object.assign(form, response.data)
    open.value = true
    title.value = "修改VIP套餐"
  })
}

/** 提交按钮 */
function submitForm() {
  if (!formRef.value) return
  
  formRef.value.validate(valid => {
    if (valid) {
      if (form.id != null) {
        updatePackage(form).then(_response => {
          proxy.$modal.msgSuccess("修改成功")
          open.value = false
          getList()
        })
      } else {
        addPackage(form).then(_response => {
          proxy.$modal.msgSuccess("新增成功")
          open.value = false
          getList()
        })
      }
    }
  })
}

/** 删除按钮操作 */
function handleDelete(row) {
  const deleteIds = row.id || ids.value
  proxy.$modal.confirm('是否确认删除VIP套餐编号为"' + deleteIds + '"的数据项？').then(function() {
    return delPackage(deleteIds)
  }).then(() => {
    getList()
    proxy.$modal.msgSuccess("删除成功")
  }).catch(() => {})
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download('system/package/export', {
    ...queryParams
  }, `package_${new Date().getTime()}.xlsx`)
}

// 初始化
getList()

// 添加一个工具函数用于字典标签显示
const dictLabel = (value, options) => {
  const item = options.find(dict => dict.value === value)
  return item ? item.label : ''
}
</script>
